#encoding:utf8
import time
import random
import hashlib
import requests
import urllib
import json
def hex_md5(data):
    md5 = hashlib.md5()
    md5.update(data.encode('utf-8'))
    md5_value = md5.hexdigest()
    return md5_value

def go(ORDERID,PAYMENT,MERCHANTID,POSID,PUBKEY):
	#MERCHANTID="105655200000097"
	#POSID="007188918"
	BRANCHID="510000000"
	CURCODE="01"
	TXCODE="530550"
	REMARK1=""
	REMARK2=""
	RETURNTYPE="4";
	TIMEOUT="";
	bankURL="https://ibsbjstar.ccb.com.cn/CCBIS/ccbMain?CCB_IBSVersion=V6"
	#PUBKEY="6dde1962a5664e1fb4098d7d020111"

	tmp = 'MERCHANTID='+MERCHANTID+'&POSID='+POSID+'&BRANCHID='+BRANCHID+'&ORDERID='+ORDERID;
	tmp += '&PAYMENT='+PAYMENT+'&CURCODE='+CURCODE+'&TXCODE='+TXCODE+'&REMARK1='+REMARK1;
	tmp += '&REMARK2='+REMARK2+'&RETURNTYPE='+RETURNTYPE+'&TIMEOUT='+TIMEOUT;

	tmp0 = tmp;
	tmp += '&PUB='+PUBKEY;

	URL = bankURL+'&'+tmp0+'&MAC='+hex_md5(tmp);
	return URL

    
	
	
	
def run_pay(ORDERID,PAYMENT,MERCHANTID,POSID,PUBKEY):
	PAYMENT=str(PAYMENT)
	url=go(ORDERID,PAYMENT,MERCHANTID,POSID,PUBKEY)
	tmp=requests.get(url,timeout=5)
	if not tmp.status_code == 200:
		return "系统不能联系银行，请找您的系统管理员处理[01]!"
	tmp=tmp.text
	tmp=json.loads(tmp)
	if tmp["SUCCESS"] == "true":
		PAYURL=tmp["PAYURL"]
		tmp=requests.get(PAYURL,timeout=5)
		if not tmp.status_code ==200:
			return "系统不能联系银行，请找您的系统管理员处理[03]!"
		tmp=tmp.text
		tmp=json.loads(tmp)
		if not tmp["SUCCESS"] == "true":
			return "系统不能联系银行，请找您的系统管理员处理[04]!"
		QRURL=tmp["QRURL"]
		return urllib.unquote(QRURL)
	else:
		print (tmp)
		return "系统不能联系银行，请找您的系统管理员处理[02]!"

if  __name__=='__main__':
	_date=time.strftime("%Y%m%d%H%M%S",time.localtime())
	print run_pay("CYNFSY-{date}-{r1}-{r2}".format(date=_date,r1=random.randint(11111,11111),r2=random.randint(1111,9999)),"0.01")
